package com.deschen.security.core.validate.code.sms;

import com.deschen.security.core.properties.SecurityProperties;
import com.deschen.security.core.properties.SmsCodeProperties;
import com.deschen.security.core.validate.code.ValidateCode;
import com.deschen.security.core.validate.code.generator.ValidateCodeGenerator;
import lombok.Data;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.*;
import java.util.Random;

/**
 * @Author deschen
 * @Create 2019/8/18
 * @Description 短信验证码生成器
 * @Since 1.0.0
 */
@Data
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {

    private SecurityProperties securityProperties;

    @Override
    public ValidateCode createValidateCode(ServletWebRequest servletWebRequest) {
        SmsCodeProperties smsCodeProperties = securityProperties.getCode().getSms();

        int length = ServletRequestUtils.getIntParameter(servletWebRequest.getRequest(), "length",
                smsCodeProperties.getLength());

        Random random = new Random();

        String sRand = "";
        for (int i = 0; i < length; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }

        return new ValidateCode(sRand, smsCodeProperties.getExpireIn());
    }



}
